<?php
// +----------------------------------------------------------------------
// | Azthink通用开发平台 [ TOMORROW IS ANOTHER DAY ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 http://www.azthink.top All rights reserved.
// +----------------------------------------------------------------------
// | Author 李忠<azthink@qq.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Model;
use app\common\model\Tree;
use think\Session;

/**
 * 菜单模型
 * @author 李忠<azthink@qq.com>
 * @createAt 2018-08-31 18:11:41
 */
class Menu extends Model {
    // 设置当前模型对应的完整数据表名称
    protected $table = '__SYS_MENU__';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //数据自动完成
    protected $auto = ['update_by' => UID, 'url'];

    public function setUrlAttr($value) {
        return strtolower($value);
    }

    //修改器
    public function getStatusTextAttr($value, $data) {
        return get_status_html($data['status']);
    }

    public function getIconTextAttr($value, $data) {
        if ($data['icon'] != '') {
            return '<i class="' . $data['icon'] . '"></i>';
        } else {
            return '<span></span>';
        }
    }

    public function getIsDevTextAttr($value, $data) {
        return get_config_text('yes_no', $data['is_dev']);
    }

    public function getIsMenuTextAttr($value, $data) {
        return get_config_text('yes_no', $data['is_menu']);
    }

    public function getModuleTextAttr($value, $data) {
        return get_config_text('menu_module_list', $data['module']);
    }

    public function getHideTextAttr($value, $data) {
        return get_config_text('yes_no', $data['hide']);
    }

    //自定义方法
    public static function lists($module, $pid = 0, $title) {
        $map = array();
        array_push($map, ['a.status', '=', 1]);
        array_push($map, ['a.pid', '=', $pid]);
        if ($module !== '' && !empty($module)) {
            array_push($map, ['a.module', '=', $module]);
        }

        if ($title !== '' && !empty($title)) {
            array_push($map, ['a.title', 'like', $title]);
        }
        return Menu::alias('a')
            ->leftjoin('__SYS_MENU__ b', 'a.pid = b.id')
            ->where($map)
            ->field('a.*, b.title as parent_title, (select count(1) from ' . self::getTable('sys_menu') . ' c where c.pid = a.id and c.status>=0) as child_count')
            ->order('a.sort')->paginate();
    }

    public static function state($id, $status) {
        return Menu::where('id', $id)->update(['status' => $status]);
    }


    // 将Menu菜单转换为树
    public static function toFormatTree($module) {
        $list = self::where(array(['status', '=', 1], ['module', '=', $module], ['is_menu', '=', 1]))->order('sort')->field('id,pid,title')->select();

        $treeModel = new Tree();
        $tree_list = $treeModel->toFormatTree($list->toArray());
        return $tree_list;
    }

    // 将Menu菜单转换为配置下拉数据
    public function listToConfig() {
        return list_to_config($this->toFormatTree(), 'id', 'title_show');
    }

    // 将Menu菜单转换为配置下拉数据
    public function listToConfigAppendFirst() {
        $tree_list = $this->toFormatTree();
        $tree_list = array_merge(array(
            0 => array(
                'id' => 0,
                'title_show' => '顶级分类'
            )
        ), $tree_list);
        return list_to_config($tree_list, 'id', 'title_show');
    }

    // 将Menu菜单转换为树
    public function toTree() {
        $list = Menu::where('status', 1)->order('sort')->field('id,pid,title')->select();
        $tree_list = model('Tree')->toTree($list);
        return $tree_list;
    }

    public static function getMenus($type) {

        $module = request()->module();
        $controller = request()->controller();
        $action = request()->action();

        $url = strtolower($module . '/' . $controller . '/' . $action);

        $menus = session('menus_' . md5($url));

        //$menus = null;
        if (!$menus) {
            $topMenus = self::getTopMenus($type, $url);
            $subMenus = self::getSubMenus($type, $url);
            $topMenu = null;
            foreach ($topMenus as $menu) {
                if ($menu['active'] == 'active') {
                    $topMenu = $menu;
                    break;
                }

            }
            $menus = array('top_menu' => $topMenu, 'top_menus' => $topMenus, 'sub_menus' => $subMenus);

            //非调试模式启用session
            if (config('app_debug') == false) {
                session('sub_menus_' . md5($url), $menus);
            }
        }
        return $menus;

    }

    /**
     * 获取顶部节点
     *
     * @param string $max
     *            最多返回多少个
     * @param string $cache_tag
     *            缓存标签
     * @return array
     */
    private static function getTopMenus($module, $url) {

        $topMenu = self::where(array(['status', '=', 1], ['module', '=', $module], ['url', 'like', '%' . $url . '%']))
            ->field('id,title,pid,icon')->order('pid desc')->find();
        while ($topMenu['pid'] != 0) {
            $topMenu = self::where(array(['status', '=', 1], ['module', '=', $module], ['id', '=', $topMenu['pid']]))
                ->field('id,title,pid,icon')->order('pid desc')->find();
        }


        if (is_admin()) {
            $menus = self::alias('a')
                ->where(array(['a.status', '=', 1], ['a.module', '=', $module], ['a.is_menu', '=', 1], ['a.pid', '=', 0]))
                ->field('a.id,a.title, a.url,a.icon')->order('a.sort')->select();
            $length = count($menus);
            for ($i = 0; $i < $length; $i++) {
                $menus[$i]['active'] = '';
                if ($menus[$i]['id'] == $topMenu['id']) {
                    $menus[$i]['active'] = 'active';
                }
            }
        } else {
            $menus = self::alias('a')
                ->where(array(['a.status', '=', 1], ['a.module', '=', $module], ['a.is_menu', '=', 1], ['a.pid', '=', 0], ['is_dev', '=', 0]))
                ->field('a.id,a.title, a.url,a.icon')->order('a.sort')->select();
            $auth_ids = AuthExtend::listAuthIds(UID, AuthExtend::$TYPE_MENU);
            $length = count($menus);
            for ($i = 0; $i < $length; $i++) {
                $menus[$i]['active'] = '';
                if ($menus[$i]['id'] == $topMenu['id']) {
                    $menus[$i]['active'] = 'active';
                }
                $flag = false;
                foreach ($auth_ids as $auth_id) {
                    if ($menus[$i]['id'] == $auth_id) {
                        $flag = true;
                        break;
                    }
                }
                if ($flag == false) {
                    unset($menus[$i]);
                }
            }
        }
        if ($menus) {
            return $menus->toArray();
        } else {
            return null;
        }


    }

    private static function getSubMenus($module, $url) {


        $currMenu = self::where(array(['status', '=', 1], ['pid', '<>', 0], ['module', '=', $module], ['url', 'like', '%' . $url . '%']))->order('pid')->field('id,pid')->find();

        $menus = null;
        if ($currMenu) {
            if (is_admin()) {
                $menus = self::alias('a')
                    ->where(array(['a.status', '=', 1], ['a.module', '=', $module], ['a.is_menu', '=', 1], ['a.pid', '=', $currMenu['pid']]))
                    ->field('a.id,a.title, a.url,a.icon')->order('a.sort')->select();
                $length = count($menus);
                for ($i = 0; $i < $length; $i++) {
                    $menus[$i]['active'] = '';
                    if ($currMenu['id'] == $menus[$i]['id']) {
                        $menus[$i]['active'] = 'active';
                    }

                }
            } else {
                $menus = self::alias('a')
                    ->where(array(['a.status', '=', 1], ['a.module', '=', $module], ['a.is_menu', '=', 1], ['a.pid', '=', $currMenu['pid']], ['a.is_dev', '=', 0]))
                    ->field('a.id,a.title, a.url,a.icon')->order('a.sort')->select();

                $auth_ids = AuthExtend::listAuthIds(UID, AuthExtend::$TYPE_MENU);
                $length = count($menus);

                for ($i = 0; $i < $length; $i++) {
                    $menus[$i]['active'] = '';
                    if ($currMenu['id'] == $menus[$i]['id']) {
                        $menus[$i]['active'] = 'active';
                    }

                    $flag = false;
                    foreach ($auth_ids as $auth_id) {
                        if ($menus[$i]['id'] == $auth_id) {
                            $flag = true;

                            break;
                        }
                    }
                    if ($flag == false) {
                        unset($menus[$i]);
                    }

                }
            }
        }

        if ($menus) {
            return $menus->toArray();
        } else {
            return null;
        }
    }

    public static function getActionRules($user_id, $module) {

        $menus = self::alias('a')
            ->join('__AUTH_EXTEND__ b', 'a.id = b.extend_id and b.type = 2')
            ->join('__AUTH_EXTEND__ c', 'b.group_id = c.group_id and c.type = 1')
            ->where(array(['a.status', '=', 1], ['a.module', '=', $module], ['a.is_menu', '=', 0], ['c.extend_id', '=', $user_id]))
            ->field('DISTINCT a.id,a.title, a.url')->order('a.sort')->select();

        $action_rules = [];
        foreach ($menus as $menu) {
            array_push($action_rules, $menu['url']);
        }
        return $action_rules;

    }
    public static function getPid($id) {
        return self::where('id', $id)->value('pid');
    }
}
